# -*- coding: utf-8 -*-
# @Time : 2022-05-23 15:21
# @Author : Z
# @Function : APP关键字
import json
import os
import threading
import time
import traceback
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from Common.Logger import logger, path
from Keywords.common import Common


class App:

    def __init__(self):
        self.port = 4723
        self.driver: webdriver.Remote = None

    def run_appium(self, appiumPath=r"F:\app\Appium", port="4723"):
        # 多线程启动appium
        try:
            if appiumPath is None or appiumPath == '':
                appiumPath = r"F:\app\Appium"
            if port is None or port == "":
                port = '4723'
            # 控制台只显示appium的error信息
            appiumPath += r"\resources\app\node_modules\appium\build\lib\main.js --port " + port + " --log-level error"
            #  将appium的信息保存到log.txt，不在控制台显示
            # appiumPath += r"\resources\app\node_modules\appium\build\lib\main.js --port " + port + " >>log.txt"

            def run_Appium(appium_path):
                # 通过命令行启动appium服务
                os.system("node " + appium_path)

            # 创建子线程
            th = threading.Thread(target=run_Appium, args=(appiumPath,))
            # 启动子线程
            th.start()
            # 等待appium服务启动完成
            time.sleep(5)
            logger.info("启动appium服务成功")
            return "启动appium服务成功"
        except:
            logger.error("启动appium服务失败，请检查配置")
            return traceback.format_exc()

    def run_app(self, conf: str = ""):
        """通过配置启动APP"""
        try:
            # 把json字符串配置，处理成字典
            conf = json.loads(conf)
            # 连接appium
            self.driver = webdriver.Remote("http://127.0.0.1:%s/wd/hub" % self.port, conf)
            # 等待APP启动完成
            self.driver.implicitly_wait(10)
            logger.info("启动APP程序成功")
            return "启动APP程序成功"
        except:
            logger.error("启动APP程序失败，请检查配置")
            return traceback.format_exc()

    def kill_appium(self):
        """关闭appium服务"""
        try:
            os.system("taskkill /F /IM node.exe")
            logger.info("关闭appium服务成功")
            return "关闭appium服务成功"
        except:
            logger.error("关闭appium服务失败")
            return traceback.format_exc()

    def __find_ele(self, locator: str = ''):
        """定位元素"""
        try:
            # id定位
            if locator.__contains__(":id/"):
                return self.driver.find_element(AppiumBy.ID,locator)
            # xpath定位
            elif locator.startswith("/"):
                return self.driver.find_element(AppiumBy.XPATH,locator)
            # accessibility定位
            else:
                return self.driver.find_element(AppiumBy.ACCESSIBILITY_ID,locator)
        except:
            return traceback.format_exc()

    def click(self, locator: str = ''):
        """点击"""
        try:
            ele = self.__find_ele(locator)
            ele.click()
            logger.info("点击" + locator)
            return "点击" + locator
        except:
            res = self.__find_ele(locator)
            logger.error("点击失败，请检查" + locator)
            return res

    def input(self, locator='', value=''):
        """输入文本"""
        try:
            ele = self.__find_ele(locator)
            # ele.click()
            ele.clear()
            ele.send_keys(value)
            logger.info(locator + "输入" + value)
            return locator + "输入" + value
        except:
            res = self.__find_ele(locator)
            logger.error("输入失败，请检查" + locator)
            return res

    def sleep(self, t='1'):
        """等待"""
        try:
            t = float(t)
            time.sleep(t)
            logger.info("等待" + str(t) + "秒")
            return "等待" + str(t) + "秒"
        except:
            logger.error("等待失败，请检查" + t)
            return traceback.format_exc()

    def quit(self):
        """关闭"""
        try:
            self.driver.quit()
            logger.info("关闭app成功")
            return "关闭成功"
        except:
            logger.error("关闭app失败")
            return traceback.format_exc()

    def back(self, t='1'):
        """按返回键，并等待t秒"""
        try:
            self.driver.back()
            self.sleep(t)
            logger.info("按返回键成功")
            return "按返回键成功"
        except:
            logger.error("按返回键失败")
            return traceback.format_exc()

    def screen_shot(self):
        """保存截图到指定文件夹"""
        try:
            common = Common()
            time = common.now_time("%Y%m%d%H%M%S")
            filename = path + r"/lib/imgs/app_imgs/" + time + ".png"
            self.driver.get_screenshot_as_file(filename)
            with open(filename, mode='rb') as f:
                file = f.read()
            logger.info("截图成功")
            return file
        except:
            logger.error("截图失败")
            return traceback.format_exc()

    def save_screen_shot(self):
        """保存截图当前目录下"""
        try:
            common = Common()
            time = common.now_time("%Y%m%d%H%M%S")
            filename = time + '.png'
            self.driver.save_screenshot(filename)
            with open(filename, mode='rb') as f:
                file = f.read()
            logger.info("截图成功")
            return file
        except:
            logger.error("截图失败")
            return traceback.format_exc()

